import React, { useState, useEffect, useRef } from "react";
import {
  Tabs,
  Row,
  Col,
  Tag,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Checkbox,
  Upload,
  message,
} from "antd";
import { PlusOutlined, UploadOutlined } from "@ant-design/icons";
import {
  fetchCategories,
  fetchSeedList,
  uploadSeed,
  getTrackerUrl,
  uploadImage,
  fetchPromotionStrategies,
} from "../api/SeedApi";
import { useNavigate } from "react-router-dom";
import "./Seed.css";
// 添加 MD 编辑器导入
import { MdEditor } from "md-editor-rt";
import "md-editor-rt/lib/style.css";
import SeedDetail from "./SeedDetail"; // 导入种子详情组件

const { TabPane } = Tabs;
const { Option } = Select;

function Seed() {
  const [form] = Form.useForm();
  const [activeCategory, setActiveCategory] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentCategory, setCurrentCategory] = useState("");
  const [selectedTags, setSelectedTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [trackerUrl, setTrackerUrl] = useState("");
  const containerRef = useRef(null);
  const navigate = useNavigate(); // 使用 useNavigate 钩子

  // 添加种子详情相关状态
  const [selectedSeedId, setSelectedSeedId] = useState(null);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);

  // 添加分类数据状态
  const [categories, setCategories] = useState([]);

  // 添加筛选策略状态
  const [promotionStrategies, setPromotionStrategies] = useState([]);
  const [selectedPromotion, setSelectedPromotion] = useState();

  useEffect(() => {
    // 获取分类数据
    const loadCategories = async () => {
      try {
        const response = await fetchCategories();
        if (response.success) {
          const sortedCategories = response.data;
          setCategories(response.data);
          if (sortedCategories.length > 0) {
            setCurrentCategory(sortedCategories[0].name);
            handleTabChange(sortedCategories[0].name);
          }
        }
      } catch (error) {
        message.error("获取分类数据失败");
      }
    };

    loadCategories();

    // 获取筛选策略
    const loadPromotionStrategies = async () => {
      try {
        const strategies = await fetchPromotionStrategies();
        if (strategies.success) {
          setPromotionStrategies(strategies.data);
          if (strategies.data.length > 0) {
            setSelectedPromotion("all");
          }
        }
      } catch (error) {
        message.error("获取筛选策略失败");
      }
    };

    loadPromotionStrategies();
  }, []);

  // 为不同类别定义不同的标签选项
  const categoryTags = {
    电影: [
      { label: "动作", value: "动作" },
      { label: "喜剧", value: "喜剧" },
      { label: "爱情", value: "爱情" },
      { label: "科幻", value: "科幻" },
      { label: "恐怖", value: "恐怖" },
      { label: "悬疑", value: "悬疑" },
      { label: "犯罪", value: "犯罪" },
      { label: "战争", value: "战争" },
      { label: "动画", value: "动画" },
      { label: "其他", value: "其他" },
    ],
    剧集: [
      { label: "国产剧", value: "国产剧" },
      { label: "美剧", value: "美剧" },
      { label: "韩剧", value: "韩剧" },
      { label: "英剧", value: "英剧" },
      { label: "日剧", value: "日剧" },
      { label: "古装剧", value: "古装剧" },
      { label: "都市剧", value: "都市剧" },
      { label: "悬疑剧", value: "悬疑剧" },
      { label: "偶像剧", value: "偶像剧" },
      { label: "其他", value: "其他" },
    ],
    综艺: [
      { label: "真人秀", value: "真人秀" },
      { label: "脱口秀", value: "脱口秀" },
      { label: "音乐综艺", value: "音乐综艺" },
      { label: "美食综艺", value: "美食综艺" },
      { label: "旅行综艺", value: "旅行综艺" },
      { label: "竞技综艺", value: "竞技综艺" },
      { label: "亲子综艺", value: "亲子综艺" },
      { label: "喜剧综艺", value: "喜剧综艺" },
      { label: "文化综艺", value: "文化综艺" },
      { label: "其他", value: "其他" },
    ],
    纪录片: [
      { label: "人文历史", value: "人文历史" },
      { label: "自然科学", value: "自然科学" },
      { label: "社会纪实", value: "社会纪实" },
      { label: "美食纪录片", value: "美食纪录片" },
      { label: "旅行纪录片", value: "旅行纪录片" },
      { label: "动物纪录片", value: "动物纪录片" },
      { label: "科技纪录片", value: "科技纪录片" },
      { label: "艺术纪录片", value: "艺术纪录片" },
      { label: "战争纪录片", value: "战争纪录片" },
      { label: "其他", value: "其他" },
    ],
    动漫: [
      { label: "日漫", value: "日漫" },
      { label: "国漫", value: "国漫" },
      { label: "热血", value: "热血" },
      { label: "治愈", value: "治愈" },
      { label: "科幻", value: "科幻" },
      { label: "恋爱", value: "恋爱" },
      { label: "奇幻", value: "奇幻" },
      { label: "冒险", value: "冒险" },
      { label: "搞笑", value: "搞笑" },
      { label: "其他", value: "其他" },
    ],
    MV: [
      { label: "流行", value: "流行" },
      { label: "摇滚", value: "摇滚" },
      { label: "嘻哈", value: "嘻哈" },
      { label: "民谣", value: "民谣" },
      { label: "电子", value: "电子" },
      { label: "爵士", value: "爵士" },
      { label: "古典", value: "古典" },
      { label: "R&B", value: "R&B" },
      { label: "金属", value: "金属" },
      { label: "其他", value: "其他" },
    ],
    体育: [
      { label: "篮球", value: "篮球" },
      { label: "足球", value: "足球" },
      { label: "网球", value: "网球" },
      { label: "羽毛球", value: "羽毛球" },
      { label: "乒乓球", value: "乒乓球" },
      { label: "排球", value: "排球" },
      { label: "田径", value: "田径" },
      { label: "游泳", value: "游泳" },
      { label: "格斗", value: "格斗" },
      { label: "其他", value: "其他" },
    ],
    软件: [
      { label: "办公软件", value: "办公软件" },
      { label: "图像处理", value: "图像处理" },
      { label: "视频编辑", value: "视频编辑" },
      { label: "音频编辑", value: "音频编辑" },
      { label: "开发工具", value: "开发工具" },
      { label: "安全软件", value: "安全软件" },
      { label: "娱乐软件", value: "娱乐软件" },
      { label: "教育软件", value: "教育软件" },
      { label: "系统工具", value: "系统工具" },
      { label: "其他", value: "其他" },
    ],
    其他: [
      { label: "生活技巧", value: "生活技巧" },
      { label: "手工制作", value: "手工制作" },
      { label: "摄影作品", value: "摄影作品" },
      { label: "创意设计", value: "创意设计" },
      { label: "汽车相关", value: "汽车相关" },
      { label: "家居装修", value: "家居装修" },
      { label: "时尚美妆", value: "时尚美妆" },
      { label: "宠物相关", value: "宠物相关" },
      { label: "园艺种植", value: "园艺种植" },
      { label: "其他", value: "其他" },
    ],
    游戏: [
      { label: "动作冒险", value: "动作冒险" },
      { label: "角色扮演", value: "角色扮演" },
      { label: "策略", value: "策略" },
      { label: "模拟", value: "模拟" },
      { label: "多人在线", value: "多人在线" },
      { label: "竞技", value: "竞技" },
      { label: "解谜", value: "解谜" },
      { label: "恐怖", value: "恐怖" },
      { label: "生存", value: "生存" },
      { label: "格斗", value: "格斗" },
    ],
    学习: [
      { label: "编程语言", value: "编程语言" },
      { label: "数学", value: "数学" },
      { label: "物理", value: "物理" },
      { label: "化学", value: "化学" },
      { label: "生物", value: "生物" },
      { label: "历史", value: "历史" },
      { label: "地理", value: "地理" },
      { label: "英语", value: "英语" },
      { label: "其他学科", value: "其他学科" },
      { label: "考证资料", value: "考证资料" },
    ],
    音乐: [
      { label: "华语", value: "华语" },
      { label: "欧美", value: "欧美" },
      { label: "日韩", value: "日韩" },
      { label: "古典", value: "古典" },
      { label: "流行", value: "流行" },
      { label: "摇滚", value: "摇滚" },
      { label: "民谣", value: "民谣" },
      { label: "电子", value: "电子" },
      { label: "嘻哈", value: "嘻哈" },
      { label: "其他", value: "其他" },
    ],
    原创: [
      { label: "原创小说", value: "原创小说" },
      { label: "原创诗歌", value: "原创诗歌" },
      { label: "原创绘画", value: "原创绘画" },
      { label: "原创音乐", value: "原创音乐" },
      { label: "原创视频", value: "原创视频" },
      { label: "原创剧本", value: "原创剧本" },
      { label: "原创摄影", value: "原创摄影" },
      { label: "原创设计", value: "原创设计" },
      { label: "原创手工艺品", value: "原创手工艺品" },
      { label: "其他原创", value: "其他原创" },
    ],
  };

  // 添加 page 状态，初始值为 1
  const [page, setPage] = useState(1);

  const fetchCategoryData = async (category, page = 1) => {
    const selectedCategory = categories.find((cat) => cat.name === category);
    if (selectedCategory) {
      const slug = selectedCategory.slug;
      try {
        const response = await fetchSeedList(slug, page);
        if (response.success) {
          return response.data.rows;
        }
      } catch (error) {
        message.error("获取种子列表失败");
        console.error("Error fetching seed list:", error);
      }
    }
    return [];
  };

  // 处理标签页切换
  const handleTabChange = async (key) => {
    console.log("切换标签页:", key);
    setCurrentCategory(key);
    setSelectedTags([]);
    setActiveCategory([]);
    setOriginalCategoryData([]);
    setHasMore(true); // 重置加载状态
    setLoading(false);
    setPage(1); // 重置页码
  };

  // 种子点击处理函数
  const handleSeedClick = (id) => {
    setSelectedSeedId(id);
    setIsDetailModalVisible(true);
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  // 添加 markdown 内容状态
  const [mdContent, setMdContent] = useState("");

  // 修改 handleFormSubmit 函数
  const handleFormSubmit = async (values) => {
    try {
      const formData = await form.validateFields();
      if (values.file && values.file[0]) {
        formData.file = values.file[0].originFileObj;
      }
      // 找到对应分类的 slug 值
      const selectedCategory = categories.find(
        (cat) => cat.name === values.category
      );
      if (selectedCategory) {
        formData.category = selectedCategory.slug;
      }
      console.log("添加表单数据:", formData);

      // 调用上传 API
      const response = await uploadSeed(formData);
      console.log("上传成功:", response);

      // 重置表单和关闭弹窗
      form.resetFields();
      setIsModalVisible(false);

      // 刷新当前类别的数据
      const newData = await fetchCategoryData(currentCategory);
      setActiveCategory(newData);
    } catch (error) {
      console.error("上传失败:", error);
      message.error("上传失败: " + error.message);
    }
  };

  // 添加原始数据状态
  const [originalCategoryData, setOriginalCategoryData] = useState([]);

  // 处理标签选择变化
  const handleTagChange = (checkedValues) => {
    setSelectedTags(checkedValues);
    // 如果没有选择任何标签，显示当前类别的所有数据
    if (checkedValues.length === 0) {
      setActiveCategory(originalCategoryData);
      return;
    }
    console.log("选中的标签:", checkedValues);
    // 根据选中的标签筛选数据
    console.log("当前类别数据:", originalCategoryData);
    const filteredData = originalCategoryData.filter((item) =>
      checkedValues.some((tag) => item.tags?.includes(tag))
    );
    console.log("过滤后的数据:", filteredData);
    setActiveCategory(filteredData);
  };

  // 删除滚动事件监听，改用 IntersectionObserver
  useEffect(() => {
    const observer = new IntersectionObserver(
      async (entries) => {
        console.log("IntersectionObserver 触发");
        if (entries[0].isIntersecting && !loading && hasMore) {
          console.log("加载更多数据");
          setLoading(true);
          try {
            console.log("当前页码:", page);
            const newData = await fetchCategoryData(currentCategory, page);

            if (newData.length === 0) {
              setHasMore(false);
            } else {
              setActiveCategory((prev) => [...prev, ...newData]);
              setOriginalCategoryData((prev) => [...prev, ...newData]);
              // 在数据加载成功后更新 page
              setPage(page + 1);
            }
          } catch (error) {
            console.error("加载更多数据失败:", error);
            message.error("加载更多数据失败");
          } finally {
            setLoading(false);
          }
        }
      },
      {
        root: document.querySelector(".layout-content"), // 使用布局容器作为观察根元素
        threshold: 0.1,
      }
    );

    const target = document.querySelector(".loading-trigger");
    if (target) {
      observer.observe(target);
    }

    return () => observer.disconnect();
  }, [page, hasMore, currentCategory]);

  // 在组件加载时获取 tracker URL
  useEffect(() => {
    getTrackerUrl().then((data) => {
      setTrackerUrl(data.trackerUrl);
    });
  }, []);

  // 添加图片上传处理函数
  const handleImageUpload = async (files, callback) => {
    const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          const form = new FormData();
          form.append("file", file);

          uploadImage(form)
            .then((res) => rev(res))
            .catch((error) => rej(error));
        });
      })
    );
    callback(res.map((item) => item.data.data));
  };

  // 添加种子详情关闭处理函数
  const handleDetailModalClose = () => {
    setIsDetailModalVisible(false);
    setSelectedSeedId(null);
  };

  // 新增：处理筛选策略改变
  const handlePromotionChange = (value) => {
    setSelectedPromotion(value);
    if (value === "all") {
      setActiveCategory(originalCategoryData);
    } else {
      const filteredData = originalCategoryData.filter(
        (item) => item.promotionType === value
      );
      setActiveCategory(filteredData);
    }
  };

  return (
    <div className="seed-container">
      {/* 种子中心标题 */}
      <h2 className="seed-title-center">种子中心</h2>

      {/* 新增：筛选策略选择框 */}
      <Select
        style={{ width: 120, marginBottom: 16 }}
        placeholder="筛选策略"
        value={selectedPromotion}
        onChange={handlePromotionChange}
      >
        <Option key="0" value="all">
          全部
        </Option>
        {promotionStrategies.map((strategy) => (
          <Option key={strategy.id} value={strategy.slug}>
            {strategy.displayName}
          </Option>
        ))}
      </Select>

      {/* 标签选择栏 */}
      <Tabs
        defaultActiveKey="游戏"
        onChange={handleTabChange}
        className="category-tabs"
      >
        {categories.map((category) => (
          <TabPane tab={category.name} key={category.name} />
        ))}
      </Tabs>

      {/* 根据当前类别显示对应的标签选项 */}
      <div style={{ margin: "4px 0" }}>
        <Checkbox.Group
          options={categoryTags[currentCategory]}
          value={selectedTags}
          onChange={handleTagChange}
          style={{ display: "flex", gap: "16px", flexWrap: "wrap" }}
        />
      </div>

      {/* 动态更新的资源列表 */}
      <div className="category-content">
        <Row gutter={[16, 16]}>
          {activeCategory.map((item) => (
            <Col span={6} key={item.id}>
              <div
                className="seed-item"
                onClick={() => handleSeedClick(item.id)}
                style={{ cursor: "pointer" }}
              >
                <h4 className="seed-title">{item.title}</h4>
                <div className="seed-meta">
                  <span className="seed-downloads">
                    下载量: {item.userDownloadCount}
                  </span>
                  <span className="seed-likes">点赞: {item.likeCount}</span>
                  <span className="seed-author">
                    作者: {item.uploadUsername}
                  </span>
                </div>
                <Button
                  type="link"
                  href={item.downloadLink}
                  target="_blank"
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  下载链接
                </Button>
              </div>
            </Col>
          ))}
        </Row>

        {/* 加载触发器 */}
        <div className="loading-trigger" style={{ height: "20px" }}>
          {loading && (
            <div style={{ textAlign: "center", padding: "20px" }}>
              <span>加载中...</span>
            </div>
          )}

          {!hasMore && activeCategory.length > 0 && (
            <div
              style={{ textAlign: "center", padding: "20px", color: "#999" }}
            >
              没有更多数据了
            </div>
          )}
        </div>
      </div>

      {/* 发布种子按钮 */}
      <Button
        className="publish-button"
        type="primary"
        shape="circle"
        draggable
        onDragStart={(e) => e.dataTransfer.setData("text/plain", null)} // 防止拖拽时触发默认行为
        onDrag={(e) => {
          const button = e.target;
          button.style.left = `${e.clientX - button.offsetWidth / 2}px`;
          button.style.top = `${e.clientY - button.offsetHeight / 2}px`;
        }}
        onClick={() => setIsModalVisible(true)}
      >
        <PlusOutlined />
      </Button>

      {/* 发布种子表单弹窗 */}
      <Modal
        title="发布种子"
        visible={isModalVisible}
        onCancel={handleModalCancel}
        footer={null}
        width="80%"
      >
        {/* 添加 Tracker URL 显示 */}
        <div
          style={{
            marginBottom: "20px",
            padding: "12px",
            background: "#f5f5f5",
            borderRadius: "4px",
            color: "#ff6699",
          }}
        >
          <span style={{ fontWeight: "bold" }}>Tracker URL: </span>
          <span
            style={{
              fontFamily: "monospace",
              wordBreak: "break-all",
            }}
          >
            {trackerUrl}
          </span>
        </div>

        <Form
          form={form}
          name="torrentForm"
          layout="vertical"
          onFinish={handleFormSubmit}
        >
          <Form.Item
            label="种子标题"
            name="title"
            rules={[{ required: true, message: "请输入种子标题" }]}
            style={{ marginBottom: "2px" }}
          >
            <Input placeholder="请输入种子标题" />
          </Form.Item>

          <Form.Item
            label="选择分类"
            name="category"
            rules={[{ required: true, message: "请选择分类" }]}
            style={{ marginBottom: "2px" }}
          >
            <Select
              placeholder="请选择分类"
              onChange={(value) => {
                form.setFieldsValue({ tags: [] });
              }}
            >
              {categories.map((category) => (
                <Option key={category.id} value={category.name}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          {/* 修改表单中的标签选择部分 */}
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.category !== currentValues.category
            }
          >
            {({ getFieldValue }) => {
              const currentCategory = getFieldValue("category");
              return currentCategory ? (
                <Form.Item
                  label="选择标签"
                  name="tag"
                  rules={[{ required: true, message: "请选择至少一个标签" }]}
                >
                  <Select
                    mode="tags" // 开启标签模式，支持自定义标签
                    placeholder="请选择或输入标签"
                    style={{ width: "100%" }}
                    maxTagCount={5}
                    allowClear
                    showArrow
                    // filterOption={(input, option) =>
                    //   option.label.toLowerCase().indexOf(input.toLowerCase()) >=
                    //   0
                    // }
                  >
                    {categoryTags[currentCategory]?.map((tag) => (
                      <Option key={tag.value} value={tag.value}>
                        {tag.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              ) : null;
            }}
          </Form.Item>

          {/* 修改描述输入部分 */}
          <Form.Item
            label="描述（支持 Markdown 格式）"
            name="description"
            rules={[{ required: true, message: "请输入描述" }]}
            style={{ marginBottom: "2px" }}
          >
            <div data-color-mode="light">
              <MdEditor
                value={mdContent}
                onChange={(content) => {
                  setMdContent(content);
                  // 手动触发表单字段的校验
                  form.setFieldsValue({ description: content });
                }}
                preview="live"
                height={400}
                toolbarHeight={50}
                onUploadImg={handleImageUpload}
              />
            </div>
          </Form.Item>

          <Form.Item
            label="种子文件"
            name="file"
            valuePropName="fileList"
            getValueFromEvent={(e) => (Array.isArray(e) ? e : e?.fileList)}
            rules={[{ required: true, message: "请上传种子文件" }]}
          >
            <Upload.Dragger
              name="files"
              multiple={false}
              style={{ padding: "8px 0" }}
            >
              <p className="ant-upload-drag-icon" style={{ margin: "4px 0" }}>
                <UploadOutlined />
              </p>
              <p
                className="ant-upload-text"
                style={{ margin: "4px 0", fontSize: "14px" }}
              >
                点击或拖拽文件到此处上传
              </p>
              <p
                className="ant-upload-hint"
                style={{ margin: "4px 0", fontSize: "12px" }}
              >
                支持单个文件上传
              </p>
            </Upload.Dragger>
          </Form.Item>
          <Form.Item
            style={{
              marginBottom: 0,
              textAlign: "right", // 将按钮容器靠右对齐
            }}
          >
            <Button
              type="primary"
              htmlType="submit"
              style={{
                width: "120px", // 设置按钮固定宽度，不再占满整行
              }}
            >
              发布
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 在最后添加种子详情弹窗 */}
      {selectedSeedId && (
        <SeedDetail
          id={selectedSeedId}
          visible={isDetailModalVisible}
          onClose={handleDetailModalClose}
        />
      )}
    </div>
  );
}

export default Seed;
